package util;

import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZooKeeperUtil implements Watcher {

	private static final Log log = LogFactory.getLog(ZooKeeperUtil.class);

	private static final String connectString = "192.168.164.132:2181";

	private static final int sessionTimeout = 10000;

	public static ZooKeeper zk;
	
	static{
		initZooKeeper();
	}

	public static void initZooKeeper() {
		if (zk == null) {
			try {
				zk = new ZooKeeper(connectString, sessionTimeout, new ZooKeeperUtil());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	public void process(WatchedEvent event) {

		log.info(event.getType().toString());
	}

	public static String addNode(String path) throws KeeperException, InterruptedException {
		String result =  zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		log.info("add "+path+" success:"+result);
		return result;
	}

	public static void delNode(String path) throws InterruptedException, KeeperException {
		zk.delete(path, -1);
		log.info("del "+path+" success");
	}

	public static Stat exitsNode(String path, Watcher watcher) throws KeeperException, InterruptedException {
		Stat stat =null;
		if(watcher!=null){
			stat =  zk.exists(path,watcher);
		}else{
			stat =  zk.exists(path,false);
		}
		log.info("ask "+path+" success:"+stat.toString());
		return stat;
	}
	
	public static List<String>  getChildren(String path,Watcher watcher) throws KeeperException, InterruptedException{
		List<String>  children = null;
		if(watcher!=null){
			children=zk.getChildren(path, watcher);
		}else{
			children=zk.getChildren(path, false);
		}
		StringBuffer sb = new StringBuffer();
		for(String s : children){
			sb.append(s+";");
		}
		log.info("getchildren "+path+" success:"+sb.toString());
		return children;
	}

	
	public static void setDate(String path,byte[] data) throws KeeperException, InterruptedException{
		zk.setData(path, data, -1);
	}
}
